import { Body, Controller, ParseIntPipe, Post, Req } from '@nestjs/common';
import { BaseController } from '../base/base.controller';
import { DbService } from '@app/db';
import { PageDto, RefuseDto } from './dto';
import { WithdrawalRecord } from '@app/db/entities/WithdrawalRecord';
import { FindOptionsWhere, MoreThanOrEqual, LessThanOrEqual, In } from 'typeorm';
import { DtoPipe } from '../pipes/dto/dto.pipe';
import { WithdrawalService } from './withdrawal.service';

@Controller('withdrawal')
export class WithdrawalController extends BaseController {
    constructor(
        private readonly db:DbService,
        private readonly service:WithdrawalService
    ) {
        super()
    }

    @Post('page')
    async withdrawalRecord(@Body() dto:PageDto) {
        let result:PaginationResult<WithdrawalRecord & {merchant?:string}> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<WithdrawalRecord> = {
            
        }

        if(dto.startTime || dto.endTime) {
            if(dto.startTime == dto.endTime) {
                where.createTime = dto.startTime
            }else {
                if(dto.startTime) {
                    where.createTime = MoreThanOrEqual(dto.startTime)
                }

                if(dto.endTime) {
                    where.createTime = LessThanOrEqual(dto.endTime)
                }
            }
        }

        if(dto.status !== undefined) {
            where.status = dto.status
        }

        result.total = await this.db.withdrawalRecord.count(where)

        if(result.total > 0) {
            result.rows = await this.db.withdrawalRecord.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})
            const ids:number[] = []
            result.rows.forEach(row => {
                if(!ids.includes(row.merchantId)) {
                    ids.push(row.merchantId)
                }
            })

            const merchants = await this.db.tenant.find({id : ids.length == 1 ? ids[0] : In(ids)}, ['name', 'id'])
            result.rows.forEach(row => {
                const i = merchants.findIndex(m => m.id == row.merchantId)
                if(i >= 0) {
                    row.merchant = merchants[i].name
                }
                
            })

        }

        return this.successRes(result)
    }


    @Post('pass')
    async pass(@Body('id', ParseIntPipe) id:number, @Req() {member, memberId}) {
        const r = await this.service.pass(id)
        return r === true ? this.successRes() : this.failRes()
    }


    @Post('refuse')
    async refuse(@Body(new DtoPipe({skipMissingProperties : true})) dto:RefuseDto, @Req() {member, memberId}) {
        const r = await this.service.refuse(dto.id, dto.reason)
        return r === true ? this.successRes() : this.failRes()
    }
}
